﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using ThoiTrang.Business;
using System.Text.RegularExpressions;
using ThoiTrang.Entities;

public partial class ecard : System.Web.UI.Page
{
    protected Regex r = new Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
    protected int MsgId = 0;
    protected int AccessCode = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["aid"] == null && Request["iid"] == null)
        {
            divEmail.Visible = false;
            lnkBack.HRef = (String.IsNullOrEmpty(Request.ServerVariables["HTTP_REFERER"])) ? "" : Request.ServerVariables["HTTP_REFERER"];
            divMsg.Visible = true;
        }
        
    }

    protected override void OnInit(EventArgs e)
    {
        btnGui.Click += new EventHandler(btnGui_Click);
        //btnXemTruoc.Click += new EventHandler(btnXemTruoc_Click);
        base.OnInit(e);
    }

    protected string GetLink()
    {
        string link = "ecardtemple.aspx?";
        link += "msgid=" + MsgId;
        link += "&ac=" + MsgId;
        link += "&Style=1";
        if (op1.Checked == true) link += "&Layout=4";
        else link += "&Layout=3";        
        link += "&rqFromName=" + ten_nguoigui.Value.Trim();
        link += "&rqToName=" + ten_nguoinhan1.Value.Trim();
        link += "&in=eva-longoria-dai-dien-dau-tien-cua-bebe-sport-2007-d96410.jpg"; // +Request["in"];
        link += "&MsgHeading=" + loitua.Value;
        link += "&rqMsgText=" + noidung.Value;
        link += "&SoundName=";
        link += "&ArticleBackLink=" + Server.UrlEncode("detail.aspx?aid=" + Request["aid"] + "&ckid=" + SessionManager.GetCookie());//"http://" + Request.ServerVariables["HTTP_HOST"] + "/detail.aspx?aid=" + Request["aid"]
        return link;
    }

    protected void btnXemTruoc_Click(object sender, EventArgs e)
    {
        //Response.Redirect(GetLink());
    }

    protected void btnGui_Click(object sender, EventArgs e)
    {
        try
        {
            if (ValidateEmail())
            {
                if (!SaveData()) return;
                string link = "http://" + Request.ServerVariables["HTTP_HOST"] + "/ecard_det.aspx?msgid=" + MsgId + "&ac=" + AccessCode;
                SendEcard(ten_nguoinhan1.Value.Trim(), link, email_nguoinhan1.Value.Trim());
                if (email_nguoinhan2.Value.Trim() != "" && r.IsMatch(email_nguoinhan2.Value.Trim()))
                    SendEcard(ten_nguoinhan2.Value.Trim(), link, email_nguoinhan2.Value.Trim());
                if (email_nguoinhan3.Value.Trim() != "" && r.IsMatch(email_nguoinhan3.Value.Trim()))
                    SendEcard(ten_nguoinhan3.Value.Trim(), link, email_nguoinhan3.Value.Trim());

                divEmail.Visible = false;
                divMsg.Visible = true;
                lnkBack.HRef = "detail.aspx?aid=" + Request["aid"] + "&ckid=" + SessionManager.GetCookie();
                //Response.Redirect("ecard.aspx?ckid=" + SessionManager.GetCookie());
            }
            else
            {
                lbMsg.InnerHtml = "<p>&nbsp;</p> <p>&nbsp;Xin vui lòng nhập lại email.</p> <p>&nbsp;</p>";
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected bool SaveData()
    {
        a_eCard_Msg msg = new a_eCard_Msg();
        msg.ArticleBackLink = "http://" + Request.ServerVariables["HTTP_HOST"]+ "/detail.aspx?aid=" + Request["aid"];
        msg.DateCreated = DateTime.Now;
        msg.DateExpire = DateTime.Now.AddMonths(1);
        msg.FromEmail = email_nguoigui.Value.Trim();
        msg.FromName = ten_nguoigui.Value.Trim();
        msg.ImageName = Request["in"];
        msg.IsNotifySender = (baotinnhan.SelectedIndex == 0) ? false : true;
        if (op1.Checked == true) msg.Layout = 4;
        else msg.Layout = 3;
        msg.MsgHeading = loitua.Value.Trim();
        msg.MsgText = noidung.Value.Trim();
        msg.SoundName = "";
        msg.Style = 1;
        msg.ToEmail = email_nguoinhan1.Value.Trim();
        msg.ToName = ten_nguoinhan1.Value.Trim();

        //Gia tri tam, gia tri dung isOk=false
        bool isOk = true;
        try
        {
            string useremail = "";
            if (SessionManager.IsLogged)
            {
                a_User user = a_UserService.Geta_UserBySessionId(SessionManager.GetCookie());
                if (user != null) useremail = user.Login_Email;
            }
            //a_eCard_MsgService.UpdateOrInserta_eCard_Msg("ins", useremail, int.Parse(Request["dt"]), msg, out MsgId, out AccessCode);
            //if(MsgId > 1 && AccessCode > 0) isOk = true;
        }
        catch (Exception ex)
        {
        }
        return isOk;
    }

    protected void SendEcard(string receiver, string link, string email)
    {
        StreamReader reader = new StreamReader(Server.MapPath("EmailTemplates/Ecard.htm"));
        string content = reader.ReadToEnd();
        content = content.Replace("[SenderName]", ten_nguoigui.Value.Trim());
        content = content.Replace("[Link]", link);
        content = content.Replace("[ReceiverName]", receiver);
        string subject = String.Format("{0}: bạn có 1 thiệp số ở ThoiTrang.com",receiver);
        EmailHelper.SendMailToFriend(subject, ten_nguoigui.Value.Trim(), email_nguoigui.Value.Trim(), email, content);
    }

    protected void SendEcardMessage()
    {
        StreamReader reader = new StreamReader(Server.MapPath("EmailTemplates/EcardMessage.htm"));
        string content = reader.ReadToEnd();
        content = content.Replace("[SenderName]", ten_nguoigui.Value.Trim());
        content = content.Replace("[ReceiverName]", ten_nguoinhan1.Value.Trim());
        string subject = "Thiệp số thời trang đã được xem!";
        EmailHelper.SendMailToFriend(subject, ten_nguoigui.Value.Trim(), email_nguoigui.Value.Trim(), email_nguoinhan1.Value, content);
    }

    protected bool ValidateEmail()
    {
        if (email_nguoigui.Value.Trim() == "" || !r.IsMatch(email_nguoigui.Value))
            return false;
        else if (email_nguoinhan1.Value.Trim() == "" || (email_nguoinhan1.Value.Trim() != "" && !r.IsMatch(email_nguoinhan1.Value)))
            return false;
        return true;
    }
}
